<template>
  <!-- 主容器，支持暗黑模式 -->
  <view class="container" :class="{ dark: isDark }">
    <!-- 自定义导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack" :hover-class="isDark ? 'dark-hover' : 'light-hover'">
        <text><</text>
      </view>
      <view class="nav-title">修改密码</view>
    </view>

    <!-- 步骤指示器 -->
    <view class="step-indicator">
      <view class="step" :class="{ 'active': currentStep >= 1 }">
        <text class="step-number">1</text>
        <text class="step-text">验证邮箱</text>
      </view>
      <view class="step-line"></view>
      <view class="step" :class="{ 'active': currentStep >= 2 }">
        <text class="step-number">2</text>
        <text class="step-text">验证身份</text>
      </view>
      <view class="step-line"></view>
      <view class="step" :class="{ 'active': currentStep >= 3 }">
        <text class="step-number">3</text>
        <text class="step-text">修改密码</text>
      </view>
    </view>

    <!-- 步骤1: 验证邮箱 -->
    <view class="step-content" v-if="currentStep === 1">
      <view class="input-group card">
        <text class="input-label">绑定邮箱：</text>
        <view class="input-with-icon">
          <input 
            class="input-field" 
            type="text"
            v-model="email" 
            placeholder="请输入绑定的邮箱"
            @blur="validateEmail"
            @input="clearError('email')"
          />
        </view>
        <text v-if="emailError" class="input-error">{{ emailError }}</text>
      </view>

      <view class="btn-next" @click="sendVerificationCode" :class="{ disabled: !canSendCode }">
        <text>获取验证码</text>
      </view>
    </view>

    <!-- 步骤2: 验证身份 -->
    <view class="step-content" v-if="currentStep === 2">
      <view class="input-group card">
        <text class="input-label">验证码：</text>
        <view class="verification-wrapper">
          <input 
            class="input-field verification-input" 
            type="number"
            v-model="verificationCode" 
            placeholder="请输入6位验证码"
            maxlength="6"
            @input="clearError('code')"
          />
          <view class="countdown" v-if="countdown > 0">
            {{ countdown }}s后重试
          </view>
        </view>
        <text v-if="verificationCodeError" class="input-error">{{ verificationCodeError }}</text>
      </view>

      <view class="btn-next" @click="verifyCode" :class="{ disabled: !canVerifyCode }">
        <text>验证</text>
      </view>
    </view>

    <!-- 步骤3: 修改密码 -->
    <view class="step-content" v-if="currentStep === 3">
      <view class="input-group card">
        <text class="input-label">当前密码：</text>
        <view class="input-with-icon">
          <input 
            class="input-field" 
            :type="showCurrentPassword ? 'text' : 'password'"
            v-model="currentPassword" 
            placeholder="请输入当前密码"
            @blur="validateCurrentPassword"
            @input="clearError('current')"
          />
          <view class="eye-icon" @click="toggleCurrentPasswordVisibility" :hover-class="isDark ? 'dark-icon-hover' : 'light-icon-hover'">
            <text>{{ showCurrentPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <text v-if="currentPasswordError" class="input-error">{{ currentPasswordError }}</text>
      </view>

      <view class="input-group card">
        <text class="input-label">新密码：</text>
        <view class="input-with-icon">
          <input 
            class="input-field" 
            :type="showNewPassword ? 'text' : 'password'"
            v-model="newPassword" 
            placeholder="请输入新密码"
            @blur="validateNewPassword"
            @input="clearError('new')"
          />
          <view class="eye-icon" @click="toggleNewPasswordVisibility" :hover-class="isDark ? 'dark-icon-hover' : 'light-icon-hover'">
            <text>{{ showNewPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <text v-if="newPasswordError" class="input-error">{{ newPasswordError }}</text>
      </view>

      <view class="password-strength" v-if="newPassword">
        <text class="strength-label">密码强度：</text>
        <view class="strength-bars">
          <view class="strength-bar" :class="{ 'active': passwordStrength >= 1 }"></view>
          <view class="strength-bar" :class="{ 'active': passwordStrength >= 2 }"></view>
          <view class="strength-bar" :class="{ 'active': passwordStrength >= 3 }"></view>
          <view class="strength-bar" :class="{ 'active': passwordStrength >= 4 }"></view>
        </view>
        <text class="strength-text">{{ passwordStrengthText }}</text>
      </view>

      <view 
        class="btn-confirm" 
        @click="submitChange" 
        :class="{ loading: isSubmitting }"
        :hover-class="isDark ? 'dark-btn-hover' : 'light-btn-hover'"
      >
        <text v-if="!isSubmitting">确认修改</text>
        <view v-if="isSubmitting" class="loading-spinner">
          <view class="spinner"></view>
        </view>
      </view>
    </view>

    <!-- 底部安全区域 -->
    <view class="bottom-safe-area"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isDark: false,
      currentStep: 1,  // 当前步骤
      email: '',
      verificationCode: '',
      currentPassword: '',
      newPassword: '',
      showCurrentPassword: false,
      showNewPassword: false,
      emailError: '',
      verificationCodeError: '',
      currentPasswordError: '',
      newPasswordError: '',
      countdown: 0,  // 验证码倒计时
      isSubmitting: false,
      verificationToken: ''  // 验证成功后获得的token
    }
  },
  
  computed: {
    // 是否可以发送验证码
    canSendCode() {
      return this.validateEmail() && this.countdown === 0
    },
    
    // 是否可以验证验证码
    canVerifyCode() {
      return this.verificationCode.length === 6
    },
    
    // 计算密码强度
    passwordStrength() {
      if (!this.newPassword) return 0
      let strength = 0
      if (this.newPassword.length >= 8) strength += 1
      if (/[a-z]/.test(this.newPassword)) strength += 1
      if (/[A-Z]/.test(this.newPassword)) strength += 1
      if (/\d/.test(this.newPassword)) strength += 1
      if (/[!@#$%^&*]/.test(this.newPassword)) strength += 1
      return strength
    },
    
    // 密码强度文本
    passwordStrengthText() {
      if (this.passwordStrength <= 1) return '弱'
      if (this.passwordStrength <= 3) return '中等'
      return '强'
    }
  },
  
  onShow() {
    const dark = getApp().globalData.darkMode || false
    this.isDark = dark
    this.setNavigationStyle(dark)
  },
  
  methods: {
    setNavigationStyle(isDark) {
      // 同之前的实现
    },

    goBack() {
      if (this.currentStep > 1) {
        this.currentStep--
      } else {
        uni.navigateBack({
          delta: 1,
          fail: () => {
            uni.navigateTo({ url: '/pages/settings/settings' })
          }
        })
      }
    },

    clearError(type) {
      if (type === 'email') this.emailError = ''
      if (type === 'code') this.verificationCodeError = ''
      if (type === 'current') this.currentPasswordError = ''
      if (type === 'new') this.newPasswordError = ''
    },

    validateEmail() {
      if (!this.email) {
        this.emailError = '请输入绑定的邮箱'
        return false
      }
      
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      if (!emailReg.test(this.email)) {
        this.emailError = '请输入正确的邮箱格式（如：xxx@example.com）'
        return false
      }

      this.emailError = ''
      return true
    },

    validateCurrentPassword() {
      if (!this.currentPassword) {
        this.currentPasswordError = '请输入当前密码'
        return false
      }
      if (this.currentPassword.length < 6) {
        this.currentPasswordError = '当前密码不能少于6位'
        return false
      }
      this.currentPasswordError = ''
      return true
    },

    validateNewPassword() {
      if (!this.newPassword) {
        this.newPasswordError = '新密码不能为空'
        return false
      }
      if (this.newPassword.length < 6) {
        this.newPasswordError = '新密码不能少于6位'
        return false
      }
      if (this.newPassword === this.currentPassword) {
        this.newPasswordError = '新密码不能与当前密码相同'
        return false
      }
      if (!/(?=.*[A-Za-z])(?=.*\d)/.test(this.newPassword)) {
        this.newPasswordError = '新密码建议包含字母和数字'
        return false
      }
      this.newPasswordError = ''
      return true
    },

    // 发送验证码
    async sendVerificationCode() {
      if (!this.canSendCode) return
      
      try {
        // 开始60秒倒计时
        this.countdown = 60
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)
        
        // 模拟发送验证码请求
        const res = await new Promise((resolve) => {
          setTimeout(() => {
            resolve({ status: 'success', message: '验证码已发送' })
          }, 1000)
        })
        
        if (res.status === 'success') {
          uni.showToast({
            title: '验证码已发送至您的邮箱',
            icon: 'success'
          })
          // 进入下一步
          this.currentStep = 2
        } else {
          this.countdown = 0
          clearInterval(timer)
          uni.showToast({
            title: res.message || '验证码发送失败',
            icon: 'none'
          })
        }
      } catch (err) {
        this.countdown = 0
        console.error('发送验证码失败:', err)
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
      }
    },

    // 验证验证码
    async verifyCode() {
      if (!this.canVerifyCode) return
      
      this.isSubmitting = true
      
      try {
        // 模拟验证码验证请求
        const res = await new Promise((resolve) => {
          setTimeout(() => {
            if (this.verificationCode === '123456') { // 测试用验证码
              resolve({ status: 'success', token: 'mock_verification_token' })
            } else {
              resolve({ status: 'fail', message: '验证码错误' })
            }
          }, 1000)
        })
        
        if (res.status === 'success') {
          this.verificationToken = res.token
          uni.showToast({
            title: '验证成功',
            icon: 'success'
          })
          // 进入下一步
          this.currentStep = 3
        } else {
          this.verificationCodeError = res.message || '验证码错误'
        }
      } catch (err) {
        console.error('验证失败:', err)
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
      } finally {
        this.isSubmitting = false
      }
    },

    // 提交修改
    async submitChange() {
      const validCurrent = this.validateCurrentPassword()
      const validNew = this.validateNewPassword()
      
      if (!validCurrent || !validNew) {
        return
      }

      if (this.isSubmitting) return
      this.isSubmitting = true

      try {
        // 模拟修改密码请求
        const res = await new Promise((resolve) => {
          setTimeout(() => {
            resolve({ 
              status: 'success', 
              message: '密码修改成功' 
            })
          }, 1500)
        })

        if (res.status === 'success') {
          uni.showToast({
            title: '密码修改成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            this.goBack()
            this.resetForm()
          }, 2000)
        } else {
          uni.showToast({
            title: res.message || '修改失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        uni.showToast({
          title: '请求失败，请检查网络',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isSubmitting = false
      }
    },

    resetForm() {
      this.email = ''
      this.verificationCode = ''
      this.currentPassword = ''
      this.newPassword = ''
      this.showCurrentPassword = false
      this.showNewPassword = false
      this.countdown = 0
      this.currentStep = 1
    },

    toggleCurrentPasswordVisibility() {
      this.showCurrentPassword = !this.showCurrentPassword
    },

    toggleNewPasswordVisibility() {
      this.showNewPassword = !this.showNewPassword
    }
  }
}
</script>

<style lang="scss">
/* 新增样式 */
.step-indicator {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 60rpx;
  position: relative;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1;
  
  &.active {
    .step-number {
      background: #fb7e29;
      color: white;
      border-color: #fb7e29;
    }
    
    .step-text {
      color: #fb7e29;
      font-weight: 500;
    }
  }
}

.step-number {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #f0f0f0;
  border: 2rpx solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 28rpx;
  margin-bottom: 10rpx;
  transition: all 0.3s ease;
}

.step-text {
  color: #999;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

.step-line {
  position: absolute;
  height: 4rpx;
  width: 60%;
  left: 20%;
  background: #f0f0f0;
  z-index: 0;
}

.dark .step-number {
  background: #333;
  border-color: #555;
}

.dark .step-line {
  background: #333;
}

/* 验证码输入组样式 */
.verification-wrapper {
  position: relative;
}

.verification-input {
  padding-right: 180rpx !important;
}

.countdown {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 24rpx;
}

/* 下一步按钮样式 */
.btn-next {
  margin: 40rpx 32rpx;
  background: #fb7e29;
  border-radius: 24rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  user-select: none;
  transition: background 0.3s;
  
  &:active {
    background: #e66a10;
  }
  
  &.disabled {
    background: #ccc;
    cursor: not-allowed;
  }
}

/* 密码强度指示器 */
.password-strength {
  display: flex;
  align-items: center;
  margin: 20rpx 32rpx;
  padding: 20rpx 0;
}

.strength-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 20rpx;
}

.strength-bars {
  display: flex;
  gap: 8rpx;
  margin-right: 20rpx;
}

.strength-bar {
  width: 40rpx;
  height: 8rpx;
  background: #eee;
  border-radius: 4rpx;
  
  &.active {
    background: #fb7e29;
  }
}

.strength-text {
  font-size: 24rpx;
  color: #fb7e29;
}

/* 暗黑模式调整 */
.dark .strength-label,
.dark .strength-text {
  color: #aaa;
}

.dark .strength-bar {
  background: #333;
  
  &.active {
    background: #fb7e29;
  }
}

/* 保留原有样式 */
.container {
  min-height: 100vh;
  padding-bottom: env(safe-area-inset-bottom);
  background: linear-gradient(135deg, #f7f7f7 0%, #e8e8e8 100%);
  color: #333;
}

.card {
  margin: 32rpx;
  border-radius: 24rpx;
  background: white;
  box-shadow: 0 16rpx 64rpx rgba(0,0,0,0.06);
  padding: 40rpx 32rpx;
}

.input-group {
  display: flex;
  flex-direction: column;
}

.input-label {
  font-size: 28rpx;
  margin-bottom: 16rpx;
  color: #666;
}

.input-field {
  height: 72rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  border-radius: 12rpx;
  border: 1rpx solid #ccc;
  outline: none;
  color: #333;
}

.input-field:focus {
  border-color: #fb7e29;
}

.input-error {
  margin-top: 8rpx;
  color: #ff3b30;
  font-size: 24rpx;
}

.btn-confirm {
  margin: 40rpx 32rpx;
  background: #fb7e29;
  border-radius: 24rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  user-select: none;
  transition: background 0.3s;
}

.btn-confirm:active {
  background: #e66a10;
}

.btn-confirm.loading {
  background: #ffb078;
}

.dark {
  background: #121212;
  color: #ccc;
}

.dark .card {
  background: #1e1e1e;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.8);
}

.dark .input-label {
  color: #aaa;
}

.dark .input-field {
  border-color: #444;
  background: #222;
  color: #eee;
}

.dark .input-field:focus {
  border-color: #fb7e29;
}

.dark .input-error {
  color: #ff6b6b;
}

.dark .btn-confirm {
  background: #fb7e29;
  color: #fff;
}

.nav-bar {
  height: 88rpx;
  padding: 0 32rpx;
  display: flex;
  align-items: center;
  background: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.container.dark .nav-bar {
  background: #1e1e1e;
  box-shadow: none;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  color: #333;
}

.container.dark .nav-title {
  color: #fff;
}

.nav-back {
  margin-right: 20rpx;
  font-size: 40rpx;
  cursor: pointer;
  color: #333;
}

.container.dark .nav-back {
  color: #fff;
}

.bottom-safe-area {
  height: env(safe-area-inset-bottom);
}
</style>